# -*- coding: utf-8 -*-

import requests
import json
import hashlib
import time
import _thread
from urllib.parse import urlencode

"""

吖咪接口测试代码
Created on Tue Jul 27 12:41:39 2021

@author: Administrator
"""

def getHtml(url, paramss, type = "post"):
    try:
        file = open("tokenlaimiao.txt", "r")
        fileData = file.read()
        token =""
        yzt = ""
        try:
            json_to_python = json.loads(fileData)
            token = json_to_python['Data']["token"]
            cell = json_to_python['Data']["cell"]
            pwd = json_to_python['Data']["password"]
            yzt = getUrlYzt(cell, pwd)
        except Exception as e1:
            print("===json 解析出错:" +str(e1))
        file.close()
        header = {'Content-Type':'application/json; charset=UTF-8',
            "app_type":"1",
                  "version":"1.21.38-test210617-1",
                  "Authorization": token}  
        # params:{uid=40076, oid=43296, key=43296, type=0, gid=43, gift_type=1, num=1, plat=android, yzt=56070fae6b37ad772ae6ed994a082038}
        # 代理
        # prox = {}
        
        if("post" == type):
            url += yzt
            data = requests.post(url, data=paramss, headers=header, timeout=2)
        else:
            data = requests.get(url, data=paramss, headers=header, timeout=2)
        data.encoding = "utf-8"
        return data.text
    except Exception as e:
        print(str(e))
        return "异常"


# 有的接口需要yzt参数
def getYzt(mydata):
    mydata = mydata + "a4be9f32637e217fb8dbbcae75759fb3"
    return hashlib.md5(mydata.encode(encoding='UTF-8')).hexdigest()

# Url参数添加验证码
def getUrlYzt(account, password):
    cdt = str(round(time.time() * 1000))
    mydata = account + password + cdt
    yzt = hashlib.md5(mydata.encode(encoding='UTF-8')).hexdigest()
    s_act = account + "_" + password + "_" + yzt
    return "?act="+s_act+"&cdt="+cdt


# 登录之后获取用户id
def getUid():
    file = open("tokenlaimiao.txt", "r")
    fileData = file.read()
    try:
        json_to_python = json.loads(fileData)
        file.close()
        return json_to_python['Data']["uid"]
    except Exception:
        file.close()
        return ""


"""
==============================================================================
    实际用户API接口调用
==============================================================================
"""
# 登录将登录数据放在文件中
def login(phone, code="831246"): # 831246 202088
    # phone = "18782927715"
    # paramss =  '{"uid":"40026", "amount":"9800"}'
    paramss = {"code": code, "cell":phone, "did":"imei866182040064619",
               "mac":"3C:86:D1:5A:EB:13", "dev":"", "plat":"vivo_V1928A", "ver":"28_9", 
               "sys":"androidphone", "sver":"1.21.39-test210726_18", "firm":"9", 
               "mart":"android", "token":"", "ip":"192.168.0.201", "source":"and-0", 
               "yzt":getYzt(phone), "lat":"30.554378", 
               "lng":"104.07132", "city":"510100", "cityname":"成都市", 
               "state":"510000", "statename":"四川省"}
    
    dd = str(paramss)
    # print(dd)
    par = dd.encode("utf-8").decode("latin-1")
    data = getHtml(URLHOST+"yonghu/celllogin", par)
    print(data)
    file = open("tokenlaimiao.txt", "w")
    file.write(data)
    file.close()

# 注册
def register():
    paramss = {"uid": getUid(), "head": "9be153ce4134d1a19a8c4d52893baaf2/image/default/1628484904720.jpeg",
               "sex": "m", "city": "510100", "state": "510000", "asign":"", "sign":"", "back":"", "zsign":"", "share_code":""}
    text = URLHOST + "yonghu/setuserinfo"
    response = getHtml(text, json.dumps(paramss))
    print(response)

# 验证码
def getCode(cell):
    paramss = {"cell": cell, "yzt": getYzt(cell)}
    text = URLHOST + "yonghu/getloginsms"+"?cell="+cell +"&yzt="+getYzt(cell)
    response = getHtml(text, "", "get")
    print(response)
# 用户签到
def signUser():
    paramss = {"uid": getUid()}
    text = URLHOST + "yonghu/signin"
    print(getHtml(text, json.dumps(paramss)))
# 用户签到
def 七天连续签到():
    paramss = {"uid": getUid()}
    text = URLHOST + "yonghu/signuser"
    print(getHtml(text, json.dumps(paramss)))
# 直播间签到
def 直播间签到(roomkey):
    paramss = {"Uid": getUid(), "RoomKey": roomkey}
    text = URLHOST + "zhibo/signchatroom"
    print(getHtml(text, json.dumps(paramss)))
def 直播间签到奖励领取(type): # type = "s" 签到  “d” 红人
    paramss = {"uid": getUid(), "utype": "1", "type": type}
    text = URLHOST + "yonghu/receiverank"
    print(getHtml(text, json.dumps(paramss)))
# 修改用户资料
def changeUserInfo(nick,value):
    paramss = {"uid": getUid(), nick: value}
    text = URLHOST + "yonghu/updateuserinfo"
    print(getHtml(text, json.dumps(paramss)))

# 获取用户账户数据
def getacc():
    try:
        data = getHtml(URLHOST+"dingdan/getaccount?uid="+getUid(), "", "get")
        json_to_python = json.loads(data)
        print("用户ID："+getUid()+"钻石："+str(json_to_python["Data"]["all"])+"  积分余额："+str(json_to_python["Data"]["gold_all"]))
    except:
        print("获取用户数据出错")

# 积分转换钻石(不能用了)
def changeZS(num):
    paramss =  {"uid":getUid(), "amount":"9800"}
    text = URLHOST+"dingdan/exchangecurrency"
    
    # getHtml(text,paramss)
    for i in range(1, num):
        print(getHtml(text,json.dumps(paramss)))


# 送礼物
def giftsend(oid, gid, num):
    paramss = {"uid": getUid(), "oid": oid, "key": oid, "type": "0", "gid": gid, "gift_type": "3", "num": num,
               "plat": "android", "yzt": getYzt(getUid())}
    text = URLHOST + "zhibo/addgiftroom"
    print(getHtml(text, json.dumps(paramss)))
# val map = mapOf<Int, Int>(43 to 1, 42 to 1, 44 to 1, 7 to 2 , 45 to 2, 46 to 5, 47 to 5, 48 to 10)
# 跑内网
# 1.内部账号 42,47,48礼物均赠送999和520.次数至少3w次以上
# 2.普通账号42,44,43,7,赠送520至少3w次，45,46,47,48赠送999至少3w次
# def testTaskl():
#     for i in range(1, 30010):
#         giftsend(20005, 520, 42, i)
# coinsss = 0.0
# def giftsend(oid, num, gid, cs):
#     paramss = {"uid":getUid(), "oid":oid, "key":oid, "type":"0", "gid":gid, "gift_type":"1", "num":num, "plat":"android", "yzt":getYzt(getUid())}
#     text = URLHOST + "zhibo/addgiftroom"
#     response = getHtml(text, json.dumps(paramss))
#     coin = 0.0
#     global coinsss
#     try:
#         json_to_python = json.loads(response)
#         coin = json_to_python['Data']["coin"]
#     except Exception as e1:
#         print("===json 解析出错:" + str(e1))
#
#     txt = "送"+str(cs)+" 次 "+str(gid)+"   倍数X"+str(num)+"    消耗钻石"+str(num*1)+"   总共得到钻石"+ str(coin-coinsss)
#     file = open("laimiaoapp42-520.txt", "a+")
#     file.write(txt + "\n")
#     file.close()
#     coinsss = coin
#     # print(response)

# 加入房间
def joinRoom(oid):
    paramss = {"uid": getUid(), "oid": oid}
    text = URLHOST + "zhibo/joinchatroom"
    getHtml(text, json.dumps(paramss))


# 申请上麦
def shangmai(oid):
    paramss = {"uid": getUid(), "oid": oid}
    text = URLHOST + "zhibo/shangmai"
    response = getHtml(text, json.dumps(paramss))
    try:
        print(response)
        json_to_python = json.loads(response)
        result = json_to_python["ErrorMessage"]
        print("加入房间："+result)
    except Exception:
        print("加入房间json异常")

# 房间发消息
def sendMsgRoom(oid):
    paramss1 = {"nick":"弑神水军~ ","head":"9be153ce4134d1a19a8c4d52893baaf2/image/default/1628484904720.jpeg","uid":getUid(),
                "role":1,"userlevel":10,"sex":"m","anchorlevel":0,"room_key":oid,"type":"1","content":"秒天秒地秒空气入场..."}
    paramss = {"data": json.dumps(paramss1)}
    text = URLHOST + "xitong/agorartmchannel"
    response = getHtml(text, json.dumps(paramss))
    print(response)
# 关注
def 关注(oid):
    paramss = {"uid": getUid(), "oid": oid}
    text = URLHOST + "yonghu/addcare"
    print(getHtml(text, json.dumps(paramss)))
# 关注
def 取消关注(oid):
    paramss = {"uid": getUid(), "oid": oid}
    text = URLHOST + "yonghu/cancelcare?uid="+getUid() +"&oid="+oid
    print(getHtml(text, json.dumps(paramss),"get"))

from urllib.parse import unquote
# 实名认证
def 实名认证():
    # {identification_no=51132519911201581X, identification_name=张洪, uid=43386}
    paramss = {"uid": getUid(), "identification_no": "51132519911201581X", "identification_name": "张洪"}
    text = URLHOST + "yonghu/uploadcertification"
    # data_gb2312 = unquote(paramss, encoding='utf-8')
    response = getHtml(text, json.dumps(paramss))
    print(response)
# 实名认证
def 开始直播():
    # {lat=30.554227, lng=104.071163, state=510000, statename=四川省, city=510100, cityname=成都市, uid=40076, labelid=1, room_type=1}
    paramss = {"uid": getUid(), "lat": "30.554227", "lng": "104.071163", "state": "510000", "statename": "四川省",
                "city": "510100", "cityname": "成都市", "labelid": "1", "room_type": "1"}
    text = URLHOST + "zhibo/createchatroom"
    # data_gb2312 = unquote(paramss, encoding='utf-8')
    response = getHtml(text, json.dumps(paramss))
    print(response)

# =====================================直播心跳任务
def 直播心跳任务():
    # {lat=30.554227, lng=104.071163, state=510000, statename=四川省, city=510100, cityname=成都市, uid=40076, labelid=1, room_type=1}
    paramss = {"uid": getUid(), "key": getUid()}
    text = URLHOST + "zhibo/chargingroom"
    # data_gb2312 = unquote(paramss, encoding='utf-8')
    response = getHtml(text, json.dumps(paramss))
    try:
        json_to_python = json.loads(response)
        print("直播同步时间：: " + str(json_to_python["IsError"]) + "  ----  " + str(json_to_python["ErrorMessage"]))
        if 1 == json_to_python["IsError"]:
            开始直播()
    except Exception as e1:
        print("直播同步时间error ：" + str(e1))

# ======================================直播心跳任务循环
def 直播心跳任务循环(val):
    print(val)
    for i in range(1, 1000):
        time.sleep(20)
        直播心跳任务()
# ======================================测试线程
def 循环执行房间送礼物(val):
    print(val)
    for i in range(1, 1000):
        time.sleep(1)
        # giftsend("20005", 42, 1)
        # giftsend("20005", 43, 1)
        # giftsend("20005", 44, 1)

        # giftsend("20005", 64, 1) # 灰色猫币
        # giftsend("20005", 65, 1) # 褐色猫币
        # giftsend("20005", 66, 1) # 绿色猫币
        # giftsend("20005", 67, 1) # 蓝色猫币
        # giftsend("20005", 68, 1) # 金色猫币
        # giftsend("20005", 69, 1) # 橙色猫币
        # giftsend("20005", 70, 1) # 紫色猫币
        # giftsend("20005", 71, 1) # 粉色猫币
        giftsend("20005", 58, 1) # 月光恋人
        giftsend("20005", 57, 1) # 日落
# 数字转大写
def 数字转大写(val):
    str_digital = str(val)
    chinese = {'1': '①', '2': '②', '3': '③', '4': '④', '5': '⑤', '6': '⑥', '7': '⑦', '8': '⑧', '9': '⑨', '0': '〇'}
    daxiewenzi = ""
    for stritem in str_digital:
        # print(stritem)
        for item in chinese:
            # print(chinese.get(item))
            if stritem == item:
                daxiewenzi += chinese.get(item)
                break
    return daxiewenzi


def 任务一():
    oid = "20005"
    codeList = ["2972", "2817", "0576", "1760", "9733", "4656", "4408", "7689", "4960", "8198"]
    # 正式环境到 240
    # 测试环境到 341

    number = 240
    if ALLCODE == 202088:
        number = 341

    # 24 内部账号 需要验证码
    # 25-35 真人认证了的
    for i in range(222, number):
        if (i == 224) and (ALLCODE == 202088):
            # getCode(strCell)
            continue
        strCell = "13540124" + str(i)
        # getCode(strCell)
        # register()                # 注册完善资料
        # changeUserInfo("nick", "弑神水军. ~"+数字转大写(str(i)))            # 修改用户资料
        # getacc()                  # 账户余额

        login(strCell, ALLCODE)  # 登录 , codeList[i-222]
        七天连续签到()             # 七天连续签到
        if ALLCODE == 202088:
            # 测试环境才送礼物
            giftsend("20005", 7, 1)  # 七天连续签到获得棒棒糖送出去
        signUser()               # 签到
        joinRoom(oid)            # 加入房间
        # 直播间签到(oid)            # 直播间签到
        # sendMsgRoom(oid)          # 房间内发消息
        # shangmai(oid)             # 申请上麦
        # 关注(oid)
        # 取消关注(oid)
        # 实名认证()
        # 开始直播()
        # changeZS(30)
    print(数字转大写(1100987))


def 开播心跳同步():
    开始直播()
    直播间签到奖励领取("s")
    直播间签到奖励领取("d")
    # 创建两个线程
    try:
        _thread.start_new_thread(直播心跳任务循环, ("开始执行任务Thread-1", ))
    except:
        print("Error: 无法启动线程")

    while 1:
        pass


def 循环重复直播间送礼多线程操作():
    # 测试线程  测试线程  测试线程  测试线程  测试线程  测试线程
    # 创建两个线程
    try:
        _thread.start_new_thread(循环执行房间送礼物, ("开始执行任务Thread-1",))
        # _thread.start_new_thread(循环执行房间送礼物, ("开始执行任务Thread-2",))
        # _thread.start_new_thread(循环执行房间送礼物, ("开始执行任务Thread-3",))
        # _thread.start_new_thread(循环执行房间送礼物, ("开始执行任务Thread-3",))
        # _thread.start_new_thread(循环执行房间送礼物, ("开始执行任务Thread-3",))
        # _thread.start_new_thread(循环执行房间送礼物, ("开始执行任务Thread-3",))
        # _thread.start_new_thread(循环执行房间送礼物, ("开始执行任务Thread-3",))
    except:
        print("Error: 无法启动线程")
    while 1:
        pass


# 正式环境
# URLHOST = "http://api.yamizhibo.com/api/"
# ALLCODE = 831246  # 831246
# 测试环境
URLHOST = "http://apitest.yamizhibo.com/api/"
ALLCODE = 202088
# =====================================================================================================================
# main 主函数
# =====================================================================================================================
if __name__ == '__main__':

    type1 = 2
    if type1 == 1:
        任务一()
    else:
        userList = ["13540124221", "18782927715",  "17190085924"]
        # 需要先登录才能执行下面的操作
        login(userList[0], ALLCODE)  # 登录
        开播心跳同步()
        # 循环重复直播间送礼多线程操作()





